import axios from 'axios'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
 
const getFile = url => {
 return new Promise((resolve, reject) => {
  axios({
    method:'get',
    url,
    responseType: 'arraybuffer'
  }).then(data => {
    resolve(data.data)
  }).catch(error => {
    reject(error.toString())
  })
 })
}
 
export function handleBatchDownload(url) {
  const data = url
  const zip = new JSZip()
  const cache = {}
  const promises = []
  data.forEach(item => {
    const promise = getFile(item).then(data => {
      const arr_name = item.split("/")
      const file_name = arr_name[arr_name.length - 1]
      zip.file(file_name, data, { binary: true })
      cache[file_name] = data
    })
    promises.push(promise)
  })
  
  Promise.all(promises).then(() => {
    zip.generateAsync({type:"blob"}).then(content => {
      FileSaver.saveAs(content, "打包下载.zip")
    })
  })
}